package com.ak.common.aspect;

import java.lang.reflect.Method;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import com.ak.common.annotation.DataScopeEndpoint;
import com.ak.common.entity.BaseEntity;
import com.ak.common.entity.CurrentUser;
import com.ak.common.utils.AKUtil;
import com.ak.common.utils.StringUtil;

/**
 * 数据过滤处理
 *
 * @author Vean
 */
@Aspect
@Component
public class DataScopeAspect {
    /**
     * 全部数据权限
     */
    public static final String DATA_SCOPE_ALL = "1";

    /**
     * 自定数据权限
     */
    public static final String DATA_SCOPE_CUSTOM = "2";

    /**
     * 部门数据权限
     */
    public static final String DATA_SCOPE_DEPT = "3";

    /**
     * 仅本人数据权限
     */
    public static final String DATA_SCOPE_SELF = "4";

    /**
     * 配置切入点（建议注解标记在 Mapper 方法上）
     */
    @Pointcut("@annotation(com.ak.common.annotation.DataScopeEndpoint)")
    public void pointCut() {
    }

    @Before("pointCut()")
    public void doBefore(JoinPoint point){
        handleDataScope(point);
    }

    private void handleDataScope(final JoinPoint joinPoint) {
        // 获得注解
        DataScopeEndpoint controllerDataScope = getAnnotationLog(joinPoint);
        if (controllerDataScope == null) {
            return;
        }
        dataScopeFilter(joinPoint, controllerDataScope.deptAlias(), controllerDataScope.userAlias());
    }

    /**
     * 数据范围过滤
     *
     * @param joinPoint 切点
     * @param deptAlias 别名
     * @param userAlias 别名
     */
    public static void dataScopeFilter(JoinPoint joinPoint, String deptAlias, String userAlias) {
        StringBuilder sqlString = new StringBuilder();
        
        CurrentUser user = AKUtil.getCurrentUser(); // 获取当前登录用户
        if (null == user) {
            return;
        }

        String dataScope = user.getDataScope();
        
        if (DATA_SCOPE_ALL.equals(dataScope)) {
            sqlString = new StringBuilder();
        } else if (DATA_SCOPE_CUSTOM.equals(dataScope)) {
            sqlString.append(StringUtil.format(" and {}.dept_id in ( select dept_id from sys_role_dept where role_id = '{}' )", deptAlias, user.getRoleId()));
        } else if (DATA_SCOPE_DEPT.equals(dataScope)) {
            sqlString.append(StringUtil.format(" and {}.dept_id = '{}' ", deptAlias, user.getDeptId()));
        } else if (DATA_SCOPE_SELF.equals(dataScope)) {
            if (StringUtils.isNotBlank(userAlias)) {
                sqlString.append(StringUtil.format(" and {}.create_by = '{}' ", userAlias, user.getUsername()));
            } else {
                // 数据权限为仅本人且没有userAlias别名不查询任何数据
                sqlString.append(" and 1 = 0 ");
            }
        }

        if (StringUtils.isNotBlank(sqlString.toString())) {
            BaseEntity baseEntity = (BaseEntity) joinPoint.getArgs()[0];
            baseEntity.setDataScopeSQL(sqlString.toString());
        }
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private DataScopeEndpoint getAnnotationLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null) {
            return method.getAnnotation(DataScopeEndpoint.class);
        }
        return null;
    }
}
